import json
from flask import request, flash, render_template
from flask_login import current_user

from app.models.gifts import Gift
from app.models.wish import Wish
from app.view_model.book import BookCollection, Booksingle
from app.view_model.trade import TradeInfo
from . import web
from app.libs.helper import is_isbn_or_key
from app.spider.yushubook import YushuBook
from app.forms.searchform import SearchForm


@web.route('/search')
def search():
    form = SearchForm(request.args)
    books = BookCollection()
    if form.validate():
        q = form.q.data
        page = form.page.data
        isbn_or_key = is_isbn_or_key(q)
        yushu_book = YushuBook()
        if isbn_or_key == 'key':
            yushu_book.get_by_key(q, page)
        else:
            yushu_book.get_by_isbn(q)
        books.cut(yushu_book, q)
        # return json.dumps(books, default=lambda o:o.__dict__)
    else:
        flash('搜索的关键字不符合要求')
        # return jsonify(form.errors)
    return render_template('search_result.html', books=books)


@web.route('/book/<isbn>/detail/')
def book_detail(isbn):
    has_in_gifts = False
    has_in_wishes = False

    yushu_book = YushuBook()
    yushu_book.get_by_isbn(isbn)
    book = Booksingle(yushu_book.first)

    if current_user.is_authenticated:
        if Gift.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_gifts = True
        if Wish.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_wishes = True

    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()

    trade_gifts_model = TradeInfo(trade_gifts)
    trade_wishes_model = TradeInfo(trade_wishes)
    return render_template('book_detail.html', book=book, wishes=trade_wishes_model,
                           gifts=trade_gifts_model, has_in_wishes=has_in_wishes, has_in_gifts=has_in_gifts)
